//从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。 
//
// 
//
// 例如: 
//给定二叉树: [3,9,20,null,null,15,7], 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回其层次遍历结果： 
//
// [
//  [3],
//  [9,20],
//  [15,7]
//]
// 
//
// 
//
// 提示： 
//
// 
// 节点总数 <= 1000 
// 
//
// 注意：本题与主站 102 题相同：https://leetcode-cn.com/problems/binary-tree-level-order-tra
//versal/ 
// Related Topics 树 广度优先搜索 
// 👍 54 👎 0

  
package com.yun.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class CongShangDaoXiaDaYinErChaShuIiLcof {
    public static void main(String[] args) {
        Solution solution = new CongShangDaoXiaDaYinErChaShuIiLcof().new Solution();
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(9);
        TreeNode node3 = new TreeNode(20);
        TreeNode node4 = new TreeNode(15);
        TreeNode node5 = new TreeNode(7);

        node1.left = node2;
        node1.right = node3;
        node3.left = node4;
        node3.right = node5;
        System.out.println("solution.levelOrder(node1) = " + solution.levelOrder(node1));
    }
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();

        TreeNode splitNode = new TreeNode(0);
        List<Integer> per = new ArrayList<>();
        queue.add(root);
        queue.add(splitNode);
        while (!queue.isEmpty()) {
            TreeNode curNode = queue.remove();
            if (curNode == splitNode) {
                // 队列空了，不加入分隔节点不然
                if (queue.isEmpty()) {
                    break;
                }
                result.add(per);
                per = new ArrayList<>();
                queue.add(splitNode);
                continue;
            }
            if (curNode == null) {
                continue;
            }
            per.add(curNode.val);
            queue.add(curNode.left);
            queue.add(curNode.right);

        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}